package com.gtja.beoms.interceptor;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * @author Ghao
 * @date 2022/1/5
 */

@Aspect
@Component
public class TimeInterceptor {
    private Logger log = LoggerFactory.getLogger(TimeInterceptor.class);

    /**一分钟，即60000ms */
    private static final long ONE_MINUTE = 1;

    @Pointcut("@annotation(com.gtja.beoms.anno.TimeAnnotation)")
    public void timePointCut(){

    }

    /**
     * 统计方法执行耗时Around环绕通知
     * @param joinPoint 被注解切入点
     * @return
     */
    @Around("timePointCut()")
    public Object timeAround(ProceedingJoinPoint joinPoint) {
        // 定义返回对象、得到方法需要的参数
        Object obj = null;
        Object[] args = joinPoint.getArgs();
        long startTime = System.currentTimeMillis();

        try {
            obj = joinPoint.proceed(args);
        } catch (Throwable e) {
            log.error("统计某方法执行耗时环绕通知出错", e);
        }

        // 获取执行的方法名
        long endTime = System.currentTimeMillis();
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        String methodName = signature.getDeclaringTypeName() + "." + signature.getName();

        // 打印耗时的信息
        this.printExecTime(methodName, startTime, endTime);
        return obj;
    }

    /**
     * 打印方法执行耗时的信息，如果超过了一定的时间，才打印
     * @param methodName
     * @param startTime
     * @param endTime
     */
    private void printExecTime(String methodName, long startTime, long endTime) {
        long diffTime = TimeUnit.MILLISECONDS.toSeconds(endTime - startTime);
        log.info("-----" + methodName + " 方法执行耗时：" + diffTime + " s");
        System.out.println("-----" + methodName + " 方法执行耗时：" + diffTime + " s");
    }

}
